package com.dingwen.treasure.business.init;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dingwen.treasure.base.constant.RedisConstant;
import com.dingwen.treasure.base.enums.StatusEnum;
import com.dingwen.treasure.common.redis.service.RedisService;
import com.dingwen.treasure.model.entity.mybatisplus.BusinessRule;
import com.dingwen.treasure.mybatisplus.service.BusinessRuleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 　JavaScriptInit
 * 　@author dingwen
 * 　@date 2022/8/29
 */
@Component
@Slf4j
public class JavaScriptInit implements ApplicationRunner {

    /**
     * redis 服务
     */
    @Resource
    private RedisService redisService;

    /**
     * 系统配置
     */
    @Resource
    private BusinessRuleService businessRuleService;


    /**
     * 将业务规则加载到redis
     */
    private void loadBusinessRuleToRedis() {
        // 查询所有可用的系统配置信息
        LambdaQueryWrapper<BusinessRule> lambdaQueryWrap = new LambdaQueryWrapper<BusinessRule>()
                .eq(BusinessRule::getRuleState, StatusEnum.NORMAL);
        List<BusinessRule> businessRules = businessRuleService.list(lambdaQueryWrap);

        // 过滤为空的以及拼接系统配置key
        Map<String, String> businessRuleMap = new HashMap<>(businessRules.size());
        businessRules.parallelStream()
                .filter(businessRule -> ObjectUtil.isNotNull(businessRule)
                        && StrUtil.isNotBlank(businessRule.getRuleContent()))
                .forEach(businessRule -> {
                    String key = RedisConstant.BUSINESS_RULE_PREFIX.concat(businessRule.getRuleId().toString());
                    businessRuleMap.put(key, JSONUtil.toJsonStr(businessRule));
                });
        // 将规则 map 存储到redis
        redisService.setCacheMap(businessRuleMap);

        // 提交修改到通道，触发刷新到JVM内存（此处必须是JSON字符串）(分布式刷新)
        redisService.convertAndSend(RedisConstant.REDIS_REFRESH_CACHE_CHANNEL_BUSINESS_RULE, businessRuleMap);
        log.info("业务规则校验已成功加载: {}", businessRuleMap.size());

    }

    @Override
    public void run(ApplicationArguments args) {
        loadBusinessRuleToRedis();
    }
}
